class Snake{
    //蛇头
    head:HTMLElement;
    //蛇的身体集合
    bodies:HTMLCollection;
    //蛇容器
    element:HTMLElement;
    constructor() {
        this.element = document.querySelector('#snake')!
        this.head = document.querySelector('#snake>div')!; //只取第一个表示蛇头
        this.bodies = this.element.getElementsByTagName('div')!;
    }

    //获取蛇头的位置
    get X(){
        return this.head.offsetLeft
    }
    get Y(){
        return this.head.offsetTop
    }
    //设置蛇头的位置
    set X(value:number){
        //停止前进
        if(this.X === value){
            return
        }
        if(value < 0 || value > 290){
            throw new Error('撞墙了！')
        }

        //方向纠正
        console.log( value,(this.bodies[1] as HTMLElement).offsetLeft)
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value){
            console.log('掉头')
            if(value > this.X){
                value = this.X-10
            }else{
                value = this.X +10
            }
        }
        this.moveBody()
        this.head.style.left = value+'px'
        this.checkHead() //检查是否撞到身体
    }
    set Y(value:number){
        //停止前进
        if(this.Y === value){
            return
        }
        if(value < 0 || value > 290){
            throw new Error('撞墙了！')
        }
        //方向纠正
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value){
            if(value > this.Y){
                value = this.Y-10
            }else{
                value = this.Y+10
            }
        }
        this.moveBody()
        this.head.style.top = value+'px'
        this.checkHead() //检查是否撞到身体
    }

    //增加身体
    addBody(){
        this.element.insertAdjacentHTML("beforeend","<div></div>"); //添加一个元素至结尾

    }
    //身体移动
    //将后边的身体设置为前边身体的位置
    moveBody(){
        let X= 0
        for(let i = this.bodies.length-1 ; i > 0 ;i--){
          let X = (this.bodies[i-1] as HTMLElement).offsetLeft;
          let Y = (this.bodies[i-1] as HTMLElement).offsetTop;
          (this.bodies[i] as HTMLElement).style.left = X +'px';
          (this.bodies[i] as HTMLElement).style.top = Y +'px';

        }
    }
    //检查头部位置     检查蛇头坐标是否蹦到身体
    checkHead(){
        for(let i = 1;i<this.bodies.length;i++){
            let X = (this.bodies[i] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i] as HTMLElement).offsetTop;
            if(this.X === X && this.Y ===Y ){
                //蛇头撞到身体
                throw new Error('撞到身体了~~~')
            }
        }
    }
}
export default Snake;